package models

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql" //import mysql driver
	"strings"
)

//db 配置文件key值映射
const (
	dbKey         = "db::"
	driverNameKey = dbKey + "driverName"
	hostKey       = dbKey + "host"
	portKey       = dbKey + "port"
	usernameKey   = dbKey + "username"
	passwordKey   = dbKey + "password"
	databaseKey   = dbKey + "database"
	maxIdleKey    = dbKey + "maxIdle"
	maxOpenKey    = dbKey + "maxOpen"
)

//数据库参数及默认值
var (
	dbDefaultAliaName = "default"   //默认数据库别名
	driverName        = "mysql"     //默认数据库驱动
	host              = "127.0.0.1" //默认host
	port              = "3306"      //默认端口
	username          = "root"      //默认用户名
	password          = "root"      //默认密码
	encoding          = "utf8"      //默认编码
	database          = "beego"     //默认数据库名称
	maxIdle           = 30          //默认最大空闲连接
	maxOpen           = 100         //默认最大连接数
)

//orm 连接对象
var Orm orm.Ormer

/*
	初始化数据库连接
*/
func init() {
	loadDbConfig()

	// connect database
	dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", username, password, host, port, database, encoding)
	fmt.Println("dataSource:", dataSource)
	orm.RegisterDataBase(dbDefaultAliaName, driverName, dataSource, maxIdle, maxOpen)

	// register models
	models := []interface{}{
		new(User),
	}
	orm.RegisterModel(models...)

	//sync db
	orm.RunSyncdb(dbDefaultAliaName, false, true)

	//开启调试
	orm.Debug = true

	Orm = orm.NewOrm()
}

//装载配置文件的数据库配置
func loadDbConfig() {
	userDriverName := beego.AppConfig.String(driverNameKey)
	if "" != strings.TrimSpace(userDriverName) {
		driverName = userDriverName
	}

	userHost := beego.AppConfig.String(hostKey)
	if "" != strings.TrimSpace(userHost) {
		host = userHost
	}

	userPort := beego.AppConfig.String(portKey)
	if "" != strings.TrimSpace(userPort) {
		port = userPort
	}

	userUsername := beego.AppConfig.String(usernameKey)
	if "" != strings.TrimSpace(userUsername) {
		username = userUsername
	}

	userPassword := beego.AppConfig.String(passwordKey)
	if "" != strings.TrimSpace(userPassword) {
		password = userPassword
	}

	userDatabase := beego.AppConfig.String(databaseKey)
	if "" != strings.TrimSpace(userDatabase) {
		database = userDatabase
	}

	userMaxIdle, err := beego.AppConfig.Int(maxIdleKey)
	if nil == err {
		fmt.Println("userMaxIdle: ", userMaxIdle)
		maxIdle = userMaxIdle
	}

	userMaxOpen, err := beego.AppConfig.Int(maxOpenKey)
	if nil == err {
		maxOpen = userMaxOpen
	}
}
